﻿using Application.Adapter;
using Application.App.Command;
using Application.Common.Extensions;
using Application.Common.Interface;
using Application.Plugins;
using Domain.Enums;
using Domain.Options;
using MediatR;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Net.Sockets;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace Application
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddApplication(this IServiceCollection services, IConfiguration Configuration)
        {

            var timeTick = int.Parse(Configuration.GetSection($"{nameof(HeartbeatOptions)}:{nameof(HeartbeatOptions.timeTick)}").Value);
            var listenPorts = Configuration.GetSection($"{nameof(HeartbeatOptions)}:{nameof(HeartbeatOptions.ListenPorts)}").Value.Split(',')?.Select(c=>int.Parse(c));
            var IPHosts = listenPorts.Select(p => new IPHost(p)).ToList();
#if DEBUG
            IPHosts.Add(new IPHost("tcp://192.168.0.38:6638"));
#endif
            services.AddMediatR(config =>
            {
                config.RegisterServicesFromAssemblies(Assembly.GetExecutingAssembly(),typeof(OutOfWineCommand).Assembly);
            });
            var mediator = services.BuildServiceProvider().GetRequiredService<IMediator>();

            var tcpService = services.AddTcpService(() =>
            {
                return new TouchSocketConfig().SetListenIPHosts(IPHosts.ToArray())
                .SetTcpDataHandlingAdapter(() => new CustomBetweenAndDataHandlingAdapter())//配置适配器
                 .UseAspNetCoreContainer(services)                 
                 .ConfigureContainer(a =>//容器的配置顺序应该在最前面
                 {
                     a.AddConsoleLogger();//添加一个控制台日志注入（注意：在maui中控制台日志不可用）
                     a.RegisterSingleton(services);//将服务器以单例注入。便于插件或其他地方获取。
                     //a.RegisterSingleton(mediator);
                 })
                 .ConfigurePlugins(a =>
                 {
                     a.UseCheckClear().SetTick(TimeSpan.FromSeconds(timeTick));
                     a.Add<ClosePlugin>();
                     a.Add<DeviceStateHandlerPlugin>();
                     a.Add<ReceivePlugin>();//此插件就可以处理接收数据
                     a.Add<DisconnectedPlugin>();
                 });
            });


            return services;
        }
    }
}
